<template>
  <div class="folder-tree">
    <div v-if="!treeData || treeData.length === 0" class="empty-tree">
      文件夹树为空 (treeData长度: {{ treeData?.length }})
    </div>
    <el-tree
      v-else
      :data="treeData"
      :props="treeProps"
      :expand-on-click-node="false"
      :highlight-current="true"
      :current-node-key="currentFolderId"
      node-key="folderId"
      @node-click="handleNodeClick"
      @node-contextmenu="handleNodeContextMenu"
    >
      <template #default="{ node, data }">
        <div class="tree-node">
          <el-icon class="folder-icon">
            <Folder v-if="!data.expanded" />
            <FolderOpened v-else />
          </el-icon>
          <span class="node-label">{{ node.label }}</span>
          <span class="node-count" v-if="data.fileCount > 0">
            ({{ data.fileCount }})
          </span>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Folder, FolderOpened } from '@element-plus/icons-vue'
import type { CdFolderVo } from '@/types/cd'

interface Props {
  folders: CdFolderVo[]
  currentFolderId: number | string
}

interface Emits {
  (e: 'folder-select', folderId: number | string): void
  (e: 'folder-context-menu', folder: CdFolderVo, event: MouseEvent): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const treeProps = {
  children: 'children',
  label: 'folderName'
}

// 构建树形数据
const treeData = computed(() => {
  console.log('FolderTree - 接收到的folders:', props.folders)
  console.log('FolderTree - folders长度:', props.folders?.length)
  console.log('FolderTree - folders类型:', typeof props.folders)
  
  if (props.folders && props.folders.length > 0) {
    console.log('FolderTree - 第一个文件夹:', props.folders[0])
    console.log('FolderTree - 第一个文件夹的children:', props.folders[0].children)
    console.log('FolderTree - 第一个文件夹的children长度:', props.folders[0].children?.length)
  }
  
  // 后端已经返回了完整的树形结构，直接使用即可
  console.log('FolderTree - 直接使用后端返回的树形数据:', props.folders)
  return props.folders || []
})

// 构建树形结构
const buildTree = (folders: CdFolderVo[], parentId: number | string): CdFolderVo[] => {
  console.log('buildTree - 输入参数:', { folders: folders?.length, parentId, parentIdType: typeof parentId })
  
  if (!folders || folders.length === 0) {
    console.log('buildTree - 文件夹列表为空')
    return []
  }
  
  const children = folders.filter(folder => {
    // 统一转换为字符串进行比较，避免类型不匹配
    const folderParentIdStr = String(folder.parentId)
    const targetParentIdStr = String(parentId)
    const match = folderParentIdStr === targetParentIdStr
    
    console.log('buildTree - 比较:', { 
      folderId: folder.folderId, 
      folderName: folder.folderName, 
      folderParentId: folder.parentId, 
      folderParentIdStr,
      targetParentId: parentId,
      targetParentIdStr,
      match
    })
    return match
  })
  
  console.log('buildTree - 找到的子文件夹:', children.length)
  
  return children.map(folder => ({
    ...folder,
    children: buildTree(folders, folder.folderId)
  }))
}

// 节点点击处理
const handleNodeClick = (data: CdFolderVo) => {
  emit('folder-select', data.folderId)
}

// 节点右键菜单处理
const handleNodeContextMenu = (event: MouseEvent, data: CdFolderVo) => {
  emit('folder-context-menu', data, event)
}

// 监听当前文件夹变化，自动展开到当前节点
watch(() => props.currentFolderId, (newFolderId) => {
  // TODO: 实现自动展开到当前节点
}, { immediate: true })
</script>

<style scoped lang="scss">
.folder-tree {
  height: 100%;
  overflow-y: auto;
  
  .empty-tree {
    padding: 20px;
    text-align: center;
    color: #909399;
    font-size: 14px;
  }
  
  :deep(.el-tree) {
    background: transparent;
    
    .el-tree-node {
      .el-tree-node__content {
        height: 36px;
        padding: 0 8px;
        border-radius: 4px;
        margin: 2px 8px;
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        &.is-current {
          background-color: #e6f7ff;
          color: #1890ff;
        }
      }
      
      .el-tree-node__expand-icon {
        padding: 6px;
        
        &.is-leaf {
          color: transparent;
        }
      }
    }
  }
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  
  .folder-icon {
    margin-right: 8px;
    color: #409eff;
  }
  
  .node-label {
    flex: 1;
    font-size: 14px;
  }
  
  .node-count {
    font-size: 12px;
    color: #909399;
    margin-left: 8px;
  }
}
</style>
